package com.yunze.web.controller.yunze.card;

import com.alibaba.fastjson.JSON;
import com.yunze.common.core.domain.entity.SysUser;
import com.yunze.common.core.domain.model.LoginUser;
import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.utils.ServletUtils;
import com.yunze.common.utils.ip.IpUtils;
import com.yunze.common.utils.spring.SpringUtils;
import com.yunze.common.utils.yunze.AesEncryptUtil;
import com.yunze.framework.web.service.TokenService;
import com.yunze.system.service.yunze.card.IApplyUseCardService;
import com.yunze.web.core.config.MyBaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/yunze/applyUseCard")
@Slf4j
public class ApplyUseCardController extends MyBaseController {

    @Resource
    private IApplyUseCardService iApplyUseCardService;
    @Resource
    private RedisCache redisCache;

    @PostMapping(value = "/list", produces = { "application/json;charset=UTF-8" })
    @PreAuthorize("@ss.hasPermi('yunze:applyUseCard:list')")
    public String getList(@RequestBody String Pstr){

        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if(Pstr!=null){
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr =  AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject( Pstr));
            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
            SysUser currentUser = loginUser.getUser();
            List<Integer> dept_id = new ArrayList<>();
            String str_dept_id = currentUser.getDeptId().toString();
            Integer int_dept_id = Integer.parseInt(str_dept_id);
            if (currentUser.getDeptId() != 100) {
                if (Parammap.get("dept_id") != null) {
                    List<Integer> P_dept_id = (List<Integer>) Parammap.get("dept_id");
                    dept_id.addAll(P_dept_id);
                } else {
                    dept_id.add(int_dept_id);
                    Parammap.put("dept_id", dept_id);
                }
            }
            return MyRetunSuccess(iApplyUseCardService.getList(Parammap),null);
        }catch (Exception e){
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            logger.error("<br/> /yunze/applyUseCard/list  <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",e.getCause().toString());
        }
        return Myerr("获取 申请开卡 列表 操作失败!");
    }



    @PostMapping(value = "/export", produces = { "application/json;charset=UTF-8" })
    @PreAuthorize("@ss.hasPermi('yunze:applyUseCard:export')")
    public String export(@RequestBody String Pstr){

        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if(Pstr!=null){
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr =  AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject( Pstr));
            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
            SysUser currentUser = loginUser.getUser();
            List<Integer> dept_id = new ArrayList<>();
            String str_dept_id = currentUser.getDeptId().toString();
            Integer int_dept_id = Integer.parseInt(str_dept_id);
            if (currentUser.getDeptId() != 100) {
                if (Parammap.get("dept_id") != null) {
                    List<Integer> P_dept_id = (List<Integer>) Parammap.get("dept_id");
                    dept_id.addAll(P_dept_id);
                } else {
                    dept_id.add(int_dept_id);
                    Parammap.put("dept_id", dept_id);
                }
            }
            boolean bool = iApplyUseCardService.export(Parammap,currentUser);
            if(bool){
                return MyRetunSuccess(bool,"指令发送成功！");
            }else {
                return Myerr("指令发送失败……");
            }
        }catch (Exception e){
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            logger.error("<br/> /yunze/applyUseCard/list  <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",e.getCause().toString());
        }
        return Myerr("获取 申请开卡 列表 操作失败!");
    }





    @PostMapping(value = "/edit", produces = { "application/json;charset=UTF-8" })
    @PreAuthorize("@ss.hasPermi('yunze:applyUseCard:edit')")
    public String edit(@RequestBody String Pstr){

        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if(Pstr!=null){
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr =  AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject( Pstr));
            boolean bool = iApplyUseCardService.upd(Parammap);
            if(bool){
                return MyRetunSuccess(bool,"操作成功！");
            }else {
                return Myerr("操作失败……");
            }
        }catch (Exception e){
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            logger.error("<br/> /yunze/applyUseCard/list  <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",e.getCause().toString());
        }
        return Myerr("获取 申请开卡 列表 操作失败!");
    }






    @PostMapping(value = "/save", produces = {"application/json;charset=utf-8"})
    public String save(@RequestBody String Pstr) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        try {
            HashMap<String, Object> Parammap = new HashMap<String, Object>();
            if(Pstr!=null){
                Pstr = Pstr.replace("%2F", "/");//转义 /
                Pstr = Pstr.replace(" ", "+");//转义 [ ]  》 +
            }
            Pstr =  AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject((String) Pstr));

            int tems = 10;
            boolean flag = isClose(ip,"selCardOpen",tems);
            if(!flag){
                if(Parammap.get("u_name")!=null && Parammap.get("id_number")!=null && Parammap.get("id_number")!=null ){
                    boolean bool = iApplyUseCardService.add(Parammap);
                    if(bool){
                        return MyRetunSuccess(bool,"已记录 您的申请!");
                    }else {
                        return MyerrOpen("操作失败……");
                    }
                }else {
                    return MyerrOpen("参数缺失,操作取消！！……");
                }
            }else {
                return MyerrOpen("您的操作频次过于频繁 请稍后重试！");
            }
        } catch (IOException ex) {
            logger.error("<br/> yunze:applyUseCard:save IOException <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",ex.getCause().toString());
        }catch (Exception e){
            logger.error("<br/> yunze:applyUseCard:save Exception <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",e.getCause().toString());
        }
        return MyerrOpen("操作失败……");
    }



    @PostMapping(value = "/find", produces = {"application/json;charset=utf-8"})
    public String find(@RequestBody String Pstr) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        try {
            HashMap<String, Object> Parammap = new HashMap<String, Object>();
            if(Pstr!=null){
                Pstr = Pstr.replace("%2F", "/");//转义 /
                Pstr = Pstr.replace(" ", "+");//转义 [ ]  》 +
            }
            Pstr =  AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject((String) Pstr));
            int tems = 10;
            boolean flag = isClose(ip,"selCardOpen",tems);
            if(!flag){
                if(Parammap.get("id_number")!=null || Parammap.get("telephone")!=null || Parammap.get("a_no")!=null ){
                    return MyRetunSuccess(iApplyUseCardService.find(Parammap),"操作成功!");
                }else{
                    return MyerrOpen("参数缺失,操作取消！！……");
                }
            }else {
                return MyerrOpen("您的操作频次过于频繁 请稍后重试！");
            }
        } catch (IOException ex) {
            logger.error("<br/> yunze:applyUseCard:save IOException <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",ex.getCause().toString());
        }catch (Exception e){
            logger.error("<br/> yunze:applyUseCard:save Exception <br/> Pstr = " + Pstr + " <br/> ip =  " + ip + " <br/> ",e.getCause().toString());
        }
        return MyerrOpen("操作失败……");
    }





    public boolean isClose(String ip, String method, int times) {
        String key = ip + "_openAppl" + method;
        Long count = redisCache.increment(key, 1);
        if (count == 1) {
            redisCache.expire(key, 60, TimeUnit.SECONDS);
        }
        if (count > times) {
            return true;
        }
        return false;
    }


}
